const AuditLogModel = require('../models/auditLogModel')
const { success, serverError, badRequest, notFound } = require('../utils/response')
const { getLogger } = require('../logger')
const logger = getLogger('controllers.auditController')

const getAuditLogs = async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1
    const limit = parseInt(req.query.limit) || 20
    const filters = {
      action_type: req.query.action_type,
      module_code: req.query.module_code,
      business_type: req.query.business_type,
      username: req.query.username,
      dept_id: req.query.dept_id ? parseInt(req.query.dept_id) : undefined,
      start_time: req.query.start_time,
      end_time: req.query.end_time
    }

    const [logs, total] = await Promise.all([
        AuditLogModel.getAllLogs(page, limit, filters),
        AuditLogModel.getLogCount(filters)
    ]);
    success(req, res, '获取审计日志成功', {
        data:logs,
        pagination: {
            page,
            limit,
            total,
            pages: Math.ceil(total / limit)
        }
    });
  } catch (err) {
    logger.error('获取审计日志失败', { error: err })
    serverError(req, res, '获取审计日志失败')
  }
}

const getAuditLogDetail = async (req, res) => {
  try {
    const { id } = req.params
    if (!id) return badRequest(req, res, 'ID不能为空')
    const log = await AuditLogModel.getById(id)
    if (!log) return notFound(req, res, '日志不存在')
    success(req, res, '获取审计日志详情成功', log)
  } catch (err) {
    logger.error('获取审计日志详情失败', { error: err })
    serverError(req, res, '获取审计日志详情失败')
  }
}

const getOnlineUsers = async (req, res) => {
  try {
    const window = parseInt(req.query.window) || 5
    const filters = {
      username: req.query.username,
      dept_id: req.query.dept_id ? parseInt(req.query.dept_id) : undefined,
      module_code: req.query.module_code,
      action_type: req.query.action_type
    }
    const rows = await AuditLogModel.getOnlineUsers(window, filters)
    success(req, res, '获取在线用户成功', rows)
  } catch (err) {
    logger.error('获取在线用户失败', { error: err })
    serverError(req, res, '获取在线用户失败')
  }
}

const getStatistics = async (req, res) => {
  try {
    const timeRange = req.query.timeRange || 'week'; // week, month, year
    const startDate = req.query.startDate;
    const endDate = req.query.endDate;
    
    // 调用Model层方法获取所有统计数据
    const dashboardData = await AuditLogModel.getDashboardStatistics(timeRange, startDate, endDate);
    
    success(req, res, '获取统计数据成功', dashboardData);
  } catch (err) {
    logger.error('获取统计数据失败', { error: err });
    serverError(req, res, '获取统计数据失败');
  }
};

module.exports = { getAuditLogs, getAuditLogDetail, getOnlineUsers, getStatistics }